﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Controls;
using System.Windows.Input;

namespace HobSoft.SoccerBet2014.Client.Controls
{
    public class KeyBindingTextBox : TextBox
    {
        KeyGestureConverter keyGestureConverter = new KeyGestureConverter();
        KeyConverter keyConverter = new KeyConverter();

        protected bool IsKeyGesture(Key key, ModifierKeys modifiers)
        {
            if ((key < Key.F1 || key > Key.F24) && (key < Key.NumPad0 || key > Key.Divide))
            {
                if ((modifiers & (ModifierKeys.Alt | ModifierKeys.Control | ModifierKeys.Windows)) != ModifierKeys.None)
                {
                    switch (key)
                    {
                        case Key.LWin:
                        case Key.RWin:
                            break;
                        default:
                            switch (key)
                            {
                                case Key.LeftCtrl:
                                case Key.RightCtrl:
                                case Key.LeftAlt:
                                case Key.RightAlt:
                                    break;
                                default:
                                    return true;
                            }
                            break;
                    }
                    return false;
                }
                if ((key >= Key.D0 && key <= Key.D9) || (key >= Key.A && key <= Key.Z))
                {
                    return false;
                }
            }
            return true;
        }

        protected override void OnPreviewKeyDown(KeyEventArgs e)
        {
            if (IsKeyGesture(e.Key,e.KeyboardDevice.Modifiers))
            {
                var keyValue = new KeyGesture(e.Key, e.KeyboardDevice.Modifiers);
                var keyString = keyGestureConverter.ConvertToInvariantString(keyValue);
                SetValue(TextProperty, keyString);
            }
            else
            {
                var keyString = keyConverter.ConvertToInvariantString(e.Key);
                SetValue(TextProperty, keyString);
            }

            //Text = keyValue;
            e.Handled = true;
        }

        public string Watermark
        {
            get
            {
                return GetValue(TextProperty).ToString();
            }
            set
            {
                var text = GetValue(TextProperty);
                if (text != null && text.ToString() != string.Empty) return;
                SetValue(TextProperty, value);
            }
        }
    }
}
